package cn.sylinx.horm.resource.java;

import cn.sylinx.horm.exception.HORMException;
import cn.sylinx.horm.resource.io.Resources;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class ResourceParser {

    private static final Map<String, Method> nameMap = new ConcurrentHashMap<>();

    public static String parseSql(String fullMethodName, Map<String, Object> params) {
        try {
            Method method = nameMap.computeIfAbsent(fullMethodName, ResourceParser::parseMethod);
            Object sqlObject = method.invoke(null, params);
            return sqlObject.toString();
        } catch (Exception e) {
            throw new HORMException(e);
        }
    }

    private static Method parseMethod(String fullMethodName) {
        try {
            int index = fullMethodName.lastIndexOf(".");
            String className = fullMethodName.substring(0, index);
            String methodName = fullMethodName.substring(index + 1);
            Class<?> clazz = Resources.classForName(className);
            return clazz.getDeclaredMethod(methodName, Map.class);
        } catch (Exception e) {
            throw new HORMException(e);
        }
    }

}
